"""
系统工具类
提供系统性能监控、数据源检查等基础功能
"""

import os
import sys
import time
import logging
from typing import Dict, Any, Optional
from datetime import datetime

logger = logging.getLogger(__name__)

class SystemUtils:
    """系统工具类"""
    
    def __init__(self):
        """初始化系统工具"""
        self.start_time = time.time()
    
    def get_system_performance(self) -> Dict[str, Any]:
        """获取系统性能指标"""
        try:
            import psutil
            
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('.')
            
            return {
                'cpu_percent': cpu_percent,
                'memory_percent': memory.percent,
                'memory_used': memory.used / (1024 * 1024),  # MB
                'memory_total': memory.total / (1024 * 1024),  # MB
                'disk_free': disk.free / (1024 * 1024 * 1024),  # GB
                'uptime': time.time() - self.start_time
            }
        except ImportError:
            logger.warning("psutil模块未安装，无法获取系统性能指标")
            return {
                'cpu_percent': 0.0,
                'memory_percent': 0.0,
                'memory_used': 0.0,
                'memory_total': 0.0,
                'disk_free': 0.0,
                'uptime': time.time() - self.start_time
            }
        except Exception as e:
            logger.error(f"获取系统性能指标失败: {e}")
            return {
                'cpu_percent': 0.0,
                'memory_percent': 0.0,
                'memory_used': 0.0,
                'memory_total': 0.0,
                'disk_free': 0.0,
                'uptime': time.time() - self.start_time
            }
    
    def check_data_source_connectivity(self) -> Dict[str, Dict[str, Any]]:
        """检查数据源连接状态"""
        sources = {
            '东方财富API': {'connected': False, 'response_time': None, 'error': None},
            'pytdx本地': {'connected': False, 'response_time': None, 'error': None},
            'akshare接口': {'connected': False, 'response_time': None, 'error': None}
        }
        
        # 检查东方财富API
        try:
            import requests
            session = requests.Session()
            session.trust_env = False
            url = "http://push2.eastmoney.com/api/qt/clist/get"
            params = {'pn': '1', 'pz': '1'}
            start_time = time.time()
            response = session.get(url, params=params, timeout=10)
            response_time = (time.time() - start_time) * 1000
            
            if response.status_code == 200:
                sources['东方财富API']['connected'] = True
                sources['东方财富API']['response_time'] = response_time
                sources['东方财富API']['status'] = '连接正常'
            else:
                sources['东方财富API']['error'] = f"HTTP {response.status_code}"
                sources['东方财富API']['status'] = '连接失败'
        except Exception as e:
            sources['东方财富API']['error'] = str(e)
            sources['东方财富API']['status'] = '连接失败'
        
        # 检查pytdx
        try:
            from pytdx.hq import TdxHq_API
            api = TdxHq_API()
            servers = [('221.131.136.194', 7709), ('111.229.200.45', 7709)]
            
            for host, port in servers:
                try:
                    start_time = time.time()
                    if api.connect(host, port):
                        response_time = (time.time() - start_time) * 1000
                        api.disconnect()
                        sources['pytdx本地']['connected'] = True
                        sources['pytdx本地']['response_time'] = response_time
                        sources['pytdx本地']['status'] = '连接正常'
                        break
                except:
                    continue
            
            if not sources['pytdx本地']['connected']:
                sources['pytdx本地']['error'] = '所有服务器连接失败'
                sources['pytdx本地']['status'] = '连接失败'
                
        except ImportError:
            sources['pytdx本地']['error'] = 'pytdx模块未安装'
            sources['pytdx本地']['status'] = '模块未安装'
        except Exception as e:
            sources['pytdx本地']['error'] = str(e)
            sources['pytdx本地']['status'] = '连接失败'
        
        # 检查akshare
        try:
            import akshare as ak
            start_time = time.time()
            df = ak.tool_trade_date_hist_sina()
            response_time = (time.time() - start_time) * 1000
            
            if df is not None and len(df) > 0:
                sources['akshare接口']['connected'] = True
                sources['akshare接口']['response_time'] = response_time
                sources['akshare接口']['status'] = '连接正常'
            else:
                sources['akshare接口']['error'] = '返回数据为空'
                sources['akshare接口']['status'] = '连接失败'
                
        except ImportError:
            sources['akshare接口']['error'] = 'akshare模块未安装'
            sources['akshare接口']['status'] = '模块未安装'
        except Exception as e:
            sources['akshare接口']['error'] = str(e)
            sources['akshare接口']['status'] = '连接失败'
        
        return sources
    
    def get_system_info(self) -> Dict[str, Any]:
        """获取系统信息"""
        return {
            'python_version': sys.version,
            'platform': sys.platform,
            'working_directory': os.getcwd(),
            'start_time': datetime.fromtimestamp(self.start_time).strftime('%Y-%m-%d %H:%M:%S'),
            'uptime': time.time() - self.start_time
        }
    
    def check_dependencies(self) -> Dict[str, bool]:
        """检查依赖包是否安装"""
        dependencies = {
            'pandas': False,
            'numpy': False,
            'requests': False,
            'pytdx': False,
            'akshare': False,
            'matplotlib': False,
            'psutil': False
        }
        
        for package in dependencies:
            try:
                __import__(package)
                dependencies[package] = True
            except ImportError:
                dependencies[package] = False
        
        return dependencies
    
    def create_directories(self):
        """创建必要的目录"""
        directories = ['data', 'logs', 'config', 'results']
        
        for directory in directories:
            if not os.path.exists(directory):
                os.makedirs(directory)
                logger.info(f"创建目录: {directory}")
    
    def cleanup_old_files(self, directory: str, days: int = 30):
        """清理旧文件"""
        try:
            import glob
            from datetime import datetime, timedelta
            
            cutoff_time = datetime.now() - timedelta(days=days)
            pattern = os.path.join(directory, "*")
            
            for file_path in glob.glob(pattern):
                if os.path.isfile(file_path):
                    file_time = datetime.fromtimestamp(os.path.getmtime(file_path))
                    if file_time < cutoff_time:
                        os.remove(file_path)
                        logger.info(f"删除旧文件: {file_path}")
                        
        except Exception as e:
            logger.error(f"清理旧文件失败: {e}")
